#!/bin/sh

g_app_name=apm
g_log_dir=./temp/
g_log_name=${g_app_name}_status.log
# 50M
g_filemax=52428800

#获取参数
if [ $# -ge 1 ]; then
	g_app_name=$1
fi

#更改工作目录
cd `dirname $0`

#获取系统信息
function getAppInfo()
{
	local var_logfile=$1
	
	date "+%Y-%m-%d %H:%M:%S" >> ${var_logfile}
	top -n 1 | grep "Cpu" >> ${var_logfile}
	free -m | grep "Mem" >> ${var_logfile}
	df -m | grep -w "/opt" >> ${var_logfile}
	
	pidof ${g_app_name}
	if [ $? -ne 0 ]
	then
		echo "${g_app_name} not exist"
		return 1
	fi
	pidstat -urht -p $(pidof ${g_app_name} ) >> ${var_logfile}
	return 0
}

#日志文件备份
function logrotate()
{
	local var_logfile=$1
	local filesize=`stat -c %s ${var_logfile}`
	
	#echo ${filesize}
	if [ $filesize -ge ${g_filemax} ]
	then
		rm -f ${var_logfile}.bak > /dev/null 2>&1
		mv ${var_logfile} ${var_logfile}.bak 
	fi
	
	return 0
}

# 循环获取指定程序信息
mkdir -p ${g_log_dir}
while [ 0 ]
do
	# echo "get application[${g_app_name}] status"
	
	logrotate ${g_log_dir}/${g_log_name}
	getAppInfo ${g_log_dir}/${g_log_name}
	if [ $? -gt 0 ]
	then
		exit 1
	fi
	
	# sleep 1
done
